import os
import time

import requests
from flask import Flask, request, jsonify
import gradio as gr
from wenet_decode_by_model import inference
# 初始化Flask应用
app = Flask(__name__)

# 保存音频文件的目录
AUDIO_DIR = './audio_files'
if not os.path.exists(AUDIO_DIR):
    os.makedirs(AUDIO_DIR)


# Flask路由，用于接收和保存音频文件
@app.route('/upload_audio', methods=['POST'])
def upload_audio():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']

    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    if file:
        # 使用时间戳命名文件
        timestamp = int(time.time())
        filename = f"{timestamp}.wav"
        filepath = os.path.join(AUDIO_DIR, filename)

        # 保存音频文件
        file.save(filepath)
        res_str = inference(filepath)

        return jsonify({"message": res_str, "file_path": filepath}), 200


# 启动Flask和Gradio应用
if __name__ == "__main__":
    # 启动Flask应用
    app.run(debug=True, port=5000)
